package com.ibeetl.admin.console.web;

import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.entity.CoreConfig;
import com.ibeetl.admin.core.entity.CoreFile;
import com.ibeetl.admin.core.file.FileItem;
import com.ibeetl.admin.core.file.FileService;
import com.ibeetl.admin.core.service.CoreConfigService;
import com.ibeetl.admin.core.service.CorePlatformService;
import com.ibeetl.admin.core.util.*;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.admin.core.web.query.CoreConfigQuery;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.beetl.sql.core.engine.PageQuery;
import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

/**
 * 配置表 接口
 */
@Controller
public class ConfigController{

    private final Log log = LogFactory.getLog(this.getClass());
    private static final String MODEL = "/admin/config";


    @Autowired private CoreConfigService configService;
    @Autowired private CorePlatformService corePlatformService;
    
    @Autowired
    FileService fileService;
    /* 页面 */

    @GetMapping(MODEL + "/index.do")
    @Function("admin.config.query")
    @ResponseBody
    public ModelAndView index() {
        ModelAndView view = new ModelAndView("/admin/config/index.html") ;
        view.addObject("search", CoreConfigQuery.class.getName());
        return view;
    }

    @GetMapping(MODEL + "/edit.do")
    @Function("admin.config.edit")
    @ResponseBody
    public ModelAndView edit(Integer id) {
        ModelAndView view = new ModelAndView("/admin/config/edit.html");
        CoreConfig config = configService.queryById(id);
        view.addObject("config", config);
        return view;
    }

    @GetMapping(MODEL + "/add.do")
    @Function("admin.config.add")
    @ResponseBody
    public ModelAndView add() {
        ModelAndView view = new ModelAndView("/admin/config/edit.html");
        return view;
    }

    /* ajax json */

    @PostMapping(MODEL + "/list.json")
    @Function("admin.config.query")
    @ResponseBody
    public JsonResult<PageQuery> list(CoreConfigQuery condtion)
    {
        PageQuery page = condtion.getPageQuery();
        configService.queryByCondition(page);
        return JsonResult.success(page);
    }

    @PostMapping(MODEL + "/add.json")
    @Function("admin.config.add")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)CoreConfig config, HttpServletRequest request)
    {
    	return saveOrUpdate(config, request);
    }

    @PostMapping(MODEL + "/edit.json")
    @Function("admin.config.edit")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  CoreConfig config, HttpServletRequest request) {
    	return saveOrUpdate(config, request);
    }

    private JsonResult<String> saveOrUpdate(CoreConfig config, HttpServletRequest request) {
    	CoreConfig configDb = configService.queryById(config.getId());
    	CoreConfig dbTitleConfig = this.configService.getConfigByTitle(config.getTitle());

    	//如果通过标题查到的对象跟当前提交的对象的ID一致，则不检查标题
    	if (configDb != null && dbTitleConfig != null && dbTitleConfig.getId().intValue() != configDb.getId().intValue()) return new JsonResult().failMessage("此配置标题与其他已存在的配置标题重复");
    	
    	//在保存之前，判断提交的标题是否为空，如果不为空，则不能保存。
    	if (configDb == null) configDb = new CoreConfig();
    	configDb = ParamUtil.initParameterObj(request, configDb);
		
    	//保存附件的标题和链接
    	String[] attachmentIds = request.getParameterValues("attachment-id[]");
    	if (attachmentIds != null) {
    		for (String attachmentId : attachmentIds) {
    			CoreFile attachment = this.fileService.getCoreFileById(NumberUtils.toLong(attachmentId));
    			String title = request.getParameter("attachment-title-" + attachmentId);
    			String url = request.getParameter("attachment-url-" + attachmentId);
    			attachment.setTitle(title);
    			attachment.setUrl(url);
    			this.fileService.updateCoreFile(attachment);
    		}
    	}

        //保存图片的标题和链接
        String[] imageIds = request.getParameterValues("image-id[]");
        if (imageIds != null) {
            for (String imageId : imageIds) {
                CoreFile image = this.fileService.getCoreFileById(NumberUtils.toLong(imageId));
                String title = request.getParameter("image-title-" + imageId);
                String url = request.getParameter("image-url-" + imageId);
                image.setTitle(title);
                image.setUrl(url);
                this.fileService.updateCoreFile(image);
            }
        }
    	
    	int success = configService.upsert(configDb);
        if (success > 0) {
            this.corePlatformService.clearConfigCache();
            return new JsonResult().success();
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }

   
    @GetMapping(MODEL + "/view.json")
    @Function("admin.config.query")
    @ResponseBody
    public JsonResult<CoreConfig>queryInfo(Integer id) {
        CoreConfig config = configService.queryById( id);
        return  JsonResult.success(config);
    }

    @PostMapping(MODEL + "/delete.json")
    @Function("admin.config.del")
    @ResponseBody
    public JsonResult delete(String ids) {
        if (ids.endsWith(",")) {
            ids = StringUtils.substringBeforeLast(ids, ",");
        }
        List<Long> idList = ConvertUtil.str2longs(ids);
        configService.batchDelCoreConfig(idList);
        this.corePlatformService.clearConfigCache();
        return new JsonResult().success();
    }
    
    
    @PostMapping(MODEL + "/excel/export.json")
    @Function("admin.config.export")
    @ResponseBody
    public JsonResult<String> export(HttpServletResponse response,CoreConfigQuery condtion) {
        /**
         * 1)需要用你自己编写一个的excel模板
         * 2)通常excel导出需要关联更多数据，因此configService.queryByCondition方法经常不符合需求，需要重写一个为模板导出的查询
         * 3)参考ConsoleDictController来实现模板导入导出
         */
        String excelTemplate ="excelTemplates/admin/config/你的excel模板文件名字.xls";
        PageQuery<CoreConfig> page = condtion.getPageQuery();
        //取出全部符合条件的
        page.setPageSize(Integer.MAX_VALUE);
        page.setPageNumber(1);
        page.setTotalRow(Integer.MAX_VALUE);
        //本次导出需要的数据
        List<CoreConfig> list =configService.queryByCondition(page).getList();
        try(InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(excelTemplate)) {
            if(is==null) {
                throw new PlatformException("模板资源不存在："+excelTemplate);
            }
            FileItem item = fileService.createFileTemp("配置表_"+DateUtil.now("yyyyMMddHHmmss")+".xls");
            OutputStream os = item.openOutpuStream();
            Context context = new Context();
            context.putVar("list", list);
            JxlsHelper.getInstance().processTemplate(is, os, context);
            os.close();
            //下载参考FileSystemContorller
            return  JsonResult.success(item.getPath());
        } catch (IOException e) {
            throw new PlatformException(e.getMessage());
        }
        
    }
    
    @PostMapping(MODEL + "/excel/import.do")
    @Function("admin.config.import")
    @ResponseBody
    public JsonResult importExcel(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
           return JsonResult.fail();
        }
        InputStream ins = file.getInputStream();
        /*解析模板并导入到数据库里,参考DictConsoleContorller，使用jxls reader读取excel数据*/
        ins.close();
        return JsonResult.success();
    }
    
    

}
